// pages/pay/index.js
const app = getApp()
import {
  getOrderById,
  getPackageList,
  cancelOrder
} from '../../api/orderDetails';
import {
  getUserAddress
} from "../../api/address";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    order: null,//订单详情
    addressList: [],//地址列表
    submitOrder: {//表单提交数据
      username: '',
      phonenumber: '',
      address: '',
    },
    userInfo: null,//用户信息
    orderId: '',
    currentState: 0,
    orderState: ['待付款', '待上门', '已完成', '已取消'],
    product: null,
    orderTime: '',
    steps: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { orderId, state } = options;
    this.setData({ orderId, currentState: Number(state) });
    this.loadOrderDetail();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadUserAddress();
    if (this.data.product && this.data.product.id) {
      this.getProductDetail(this.data.product.id);
    }
  },

  async loadOrderDetail() {
    try {
      const res = await getOrderById(this.data.currentState, this.data.orderId);
      const order = res.data[0];
      this.setData({
        order,
        submitOrder: {
          username: order.name,
          phonenumber: order.phoneNumber,
          address: order.address,
        },
        orderTime: order.createTime,
      });
      this.getProductDetail(order.packageId);
      this.setSteps();
    } catch (e) {
      wx.showToast({ title: '订单加载失败', icon: 'none', duration: 2000 });
      console.error(e);
    }
  },

  async loadUserAddress() {
    try {
      const res = await getUserAddress();
      this.setData({ addressList: res.data });
    } catch (e) {
      wx.showToast({ title: '地址加载失败', icon: 'none', duration: 2000 });
      console.error(e);
    }
  },

  async getProductDetail(packageId) {
    try {
      const productRes = await getPackageList();
      const product = (productRes.data || []).find(item => item.id === packageId);
      this.setData({
        userInfo: app.globalData.userInfo,
        product,
      });
    } catch (e) {
      wx.showToast({ title: '商品信息加载失败', icon: 'none', duration: 2000 });
      console.error(e);
    }
  },

  setSteps() {
    const { currentState } = this.data;
    const steps = [
      { desc: '买家下单' },
      { desc: '商家接单' },
      { desc: '上门办理' },
      { desc: currentState === 3 ? '取消订单' : '交易完成' },
    ];
    this.setData({ steps });
  },

  validateOrderInfo() {
    const { username, phonenumber, address } = this.data.submitOrder;
    if (!username || !phonenumber || !address) {
      wx.showToast({ title: '请填写完整收货地址', icon: 'none', duration: 2000 });
      return false;
    }
    return true;
  },

  async pay() {
    if (!this.validateOrderInfo()) return;
    try {
      const { username, phonenumber, address, product, orderId } = this.data;
      const res = await app.http('wechat/getPayParams', 'POST', {
        username,
        phonenumber,
        address,
        productId: product.id,
        orderId,
      });
      const { timeStamp, nonceStr, packageVal, signType, paySign } = res.data;
      if (!timeStamp || !nonceStr || !packageVal || !signType || !paySign) {
        wx.showToast({ title: '支付参数错误', icon: 'none', duration: 2000 });
        return;
      }
      wx.requestPayment({
        timeStamp: String(timeStamp),
        nonceStr: String(nonceStr),
        package: String(packageVal),
        signType: String(signType),
        paySign: String(paySign),
        success: () => {
          wx.switchTab({ url: '/pages/index/index' });
        },
        fail: (err) => {
          wx.showToast({ title: '支付失败', icon: 'none', duration: 2000 });
          console.error('支付失败', err);
        },
        complete: (res) => {
          console.log('支付结束', res);
        }
      });
    } catch (err) {
      wx.showToast({ title: '获取支付信息失败', icon: 'none', duration: 2000 });
      console.error('获取预支付订单失败', err);
    }
  },

  /**
   * 取消订单
   */
  async handleCancelOrder() {
    if (this.data.currentState == 2 || this.data.currentState == 3) {
      return;
    }
    const res = await cancelOrder(this.data.orderId);
    if (res.code === 200) {
      wx.showToast({
        title: '已取消订单',
      }).then(wx.navigateBack({
        delta: 1
      }));
    } else {
      wx.showToast({
        title: '服务异常，请联系客服。',
      })
    }
  },
  // 选择收货地址
  handleChooseAddr() {
    if (this.data.currentState !== 0) {
      return;
    }
    //调用微信自带的地址管理
    wx.chooseAddress({
      success: (res) => {
        let address = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        let username = res.userName;
        let phonenumber = res.telNumber;
        console.log("联系人：" + username);
        console.log("手机号码：" + phonenumber);
        console.log("收货地址：" + address);
        this.setData({
          submitOrder: {
            username: username,
            phonenumber: phonenumber,
            address: address
          }
        });
        console.log('获取用户地址成功!')
      },
      fail: (res) => {
        console.log("收货地址获取失败！")
      },
      complete: (res) => {}
    })
  },

  // 客服
  handleKefu() {
    wx.makePhoneCall({
      phoneNumber: '13935739469',
      success: (res) => {
        console.log('拨打成功！')
      },
      fail: (res) => {
        console.log("拨打失败")
        console.log(res)
      },
      complete: (res) => {}
    })
  }
})